#include "serialdebug.h"
#include "ui_serialdebug.h"
#include <QDebug>
#include <QTime>
#include <QFileDialog>
#include <QMessageBox>

SerialDebug::SerialDebug(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::SerialDebug)
{
    ui->setupUi(this);
    this->resize(QSize(960,540));
    qDebug() << "main's thread is :" << QThread::currentThreadId();
    // 定义全局类对象
    receive_count = send_count = 0;
    SerialControler = new SerialClass();
    serialThread = new QThread();
    SerialControler->moveToThread(serialThread);

    // 连接信号槽
    connect(this, &SerialDebug::scanSerial, SerialControler, &SerialClass::ScanSerial);
    connect(SerialControler,&SerialClass::scanResult, this, &SerialDebug::showSerialCom);
    connect(SerialControler, &SerialClass::readSignal, this, &SerialDebug::readSerialData);
    connect(this, &SerialDebug::openSerial, SerialControler, &SerialClass::OpenSerial);

    // 启动新线程
    serialThread->start();
    emit scanSerial();
}

SerialDebug::~SerialDebug()
{
    serialThread->quit();
    serialThread->wait();
    delete SerialControler;
    delete ui;
}

void SerialDebug::readSerialData(const QByteArray res)
{
    qDebug()<<"Receive data:"<<res;
    if (ui->pause_box->isChecked()) return;
    // 十六进制显示判定
    QString strDisplay;
    QString temp;

    if (ui->hex_box->isChecked()){
        QByteArray str = res;
        for (int i = 0;i < str.size(); i++) {
            temp.sprintf("0x%02x ",(unsigned char)str.at(i));
            strDisplay+=temp;
            receive_count ++;
        }
        ui->textBrowser->insertPlainText(strDisplay);
        ui->textBrowser->moveCursor(QTextCursor::End);
        SerialControler->ClearReadBuf();
        ui->receivebit_count_lab->setText(QString::number(receive_count));
        readbuf.clear();
        return;
    }
    if(ui->row_data_check->isChecked()) {
        ui->textBrowser->insertPlainText(res);
        ui->textBrowser->moveCursor(QTextCursor::End);
        SerialControler->ClearReadBuf();
        ui->receivebit_count_lab->setText(QString::number(receive_count));
        readbuf.clear();
        return;
    }
    for (int i = 0; i < res.size();i++) {
        receive_count ++;
        if (res[i] != '\n') readbuf.append(res[i]);
        else{
            readbuf.append('\n');
            strDisplay = readbuf;
            if(ui->showTimeBox->isChecked()){
                QTime currentTime = QTime::currentTime();
                QString instertTime = QString::number(currentTime.hour()) + ":"+
                        QString::number(currentTime.minute())+":"+
                        QString::number(currentTime.second())+":"+
                        QString::number(currentTime.msec())+"-> ";
                ui->textBrowser->insertPlainText(instertTime);
                ui->textBrowser->moveCursor(QTextCursor::End);
            }
            emit GraphShowData(strDisplay);
            ui->textBrowser->insertPlainText(strDisplay);
            ui->textBrowser->moveCursor(QTextCursor::End);
            SerialControler->ClearReadBuf();
            ui->receivebit_count_lab->setText(QString::number(receive_count));
            readbuf.clear();
            break;
        }
    }
}

void SerialDebug::on_serial_switch_btn_clicked()
{
    if(ui->serial_switch_btn->text() == tr("打开串口")) {
        // 处理界面逻辑
        ui->serial_com_box->setEnabled(false);
        ui->baudrate_box->setEnabled(false);
        ui->databit_box->setEnabled(false);
        ui->checkbit_box->setEnabled(false);
        ui->stop_bit_box->setEnabled(false);
        ui->serial_switch_btn->setText(tr("关闭串口"));
        ui->send_btn->setEnabled(true);
        emit openSerial(ui->serial_com_box->currentText(),
                        ui->baudrate_box->currentText().toInt(),
                        ui->databit_box->currentIndex(),
                        ui->checkbit_box->currentIndex(),
                        ui->stop_bit_box->currentIndex());
    }else {
        SerialControler->CloseSerial();
        ui->serial_com_box->setEnabled(true);
        ui->baudrate_box->setEnabled(true);
        ui->databit_box->setEnabled(true);
        ui->checkbit_box->setEnabled(true);
        ui->stop_bit_box->setEnabled(true);
        ui->send_btn->setEnabled(false);
        ui->serial_switch_btn->setText(tr("打开串口"));
        // 重新扫描串口
        SerialControler->ScanSerial();
        ui->serial_com_box->clear();
        ui->serial_com_box->addItems(SerialControler->serialPortList);
    }
}

void SerialDebug::on_recount_btn_clicked()
{
   receive_count = send_count = 0;
}

void SerialDebug::on_clear_data_btn_clicked()
{
   ui->textBrowser->clear();
}

void SerialDebug::on_save_data_btn_clicked()
{
    QString file_path;
    file_path = QFileDialog::getSaveFileName(this,tr("保存文件"),"",tr("TEXT(*.txt)"));
    QFile file(file_path);
    file.open(QIODevice::WriteOnly|QIODevice::Append);
    file.write(ui->textBrowser->document()->toPlainText().toUtf8());
    file.close();
}

void SerialDebug::showSerialCom(const QStringList &strList)
{
    ui->serial_com_box->addItems(strList);
}

void SerialDebug::GraphWindowClose()
{
   connect(dataShowPtr, &showDataForGraph::MeWillClose, this, &SerialDebug::GraphWindowClose);
   disconnect(this,&SerialDebug::GraphShowData,dataShowPtr,&showDataForGraph::ReceiveShowData);
}

void SerialDebug::on_pushButton_clicked()
{
   dataShowPtr = new showDataForGraph;
   dataShowPtr->resize(QSize(1440,810));
   dataShowPtr->show();
   connect(dataShowPtr, &showDataForGraph::MeWillClose, this, &SerialDebug::GraphWindowClose);
   connect(this,&SerialDebug::GraphShowData,dataShowPtr,&showDataForGraph::ReceiveShowData);
}

void SerialDebug::on_send_btn_clicked()
{
    QByteArray send_data;
    QString temp_send_data = ui->send_text_box->toPlainText();
    if(temp_send_data.isEmpty()) QMessageBox::warning(nullptr,tr("错误"),QString("发送框内容不能为空"));
    switch (ui->end_sign_box->currentIndex()) {
    case 0:
        send_data = temp_send_data.toUtf8();
        break;
    case 1:
        send_data = temp_send_data.toLatin1();
        send_data.append('\n');
        break;
    case 2:
        send_data = temp_send_data.toLatin1();
        send_data.append('\r');
        send_data.append('\n');
        break;
    }
    if(ui->hex_send_box->isChecked()){
        send_data.clear();
        send_data = QByteArray::fromHex(temp_send_data.toLatin1().data());
    }
    SerialControler->SendData(send_data);
    send_count++;
    ui->sendbit_count_lab->setText(QString::number(send_count));
}
